<?php 

namespace Weixin\Controller;
use Common\Controller\WeixinBase;
use Common\Model\Model;

class UserController extends WeixinbaseController 
{
    /**
     * 会员中心
     */
    public function index()
    {
        $userid = $this->isLogin();
        
        $user = D('Weixin/User');
        $userInfo = $user->getUserInfo($userid);
        
        $workNum = $user->getWorkNum($userid);
        $suipaiNum = $user->getSuipaiNum($userid);
        $teachNum = $user->getTeachNum($userid);

        $type = empty($_GET['type']) ? 4 : $_GET['type'];
        $this->assign('type', $type);
        
        switch($type)
        {
            case 1:
                $this->getWork();
                break;
            case 4:
                $this->getSuipai();
                break;
            case 7:
                $this->getTeach();
                break;
            default:
                $this->getSuipai();
        }
        
        $this->assign('userInfo', $userInfo);
        $this->assign('teachNum', $teachNum);
        $this->assign('workNum', $workNum);
        $this->assign('suipaiNum', $suipaiNum);
        $this->assign('sysnum', $this->getsysmsgnum());
        $this->assign('pageType', 'user');
        $this->getJsdk();
        $this->display();
    }
    
    /**
     * 获取随手拍列表
     */
    public function getSuipai()
    {
        $userid = $this->isLogin();
        $user = D('Weixin/User');
        $count = $user->getSuipaiNum($userid);
        $page = $this->Pages($count, 4);
        
        $list = $user->getSpList($userid, $page->firstRow,$page->listRows);
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
    }
    
    /**
     * 获取食谱列表
     */
    public function getWork()
    {
        $userid = $this->isLogin();
        $user = D('Weixin/User');
        $count = $user->getWorkNum($userid);
        $page = $this->Pages($count, 5);
        
        $list = $user->getWorkList($userid, $page->firstRow, $page->listRows);
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
    }
    
    /**
     * 获取导师列表
     */
    public function getTeach()
    {
        $userid = $this->isLogin();
        $user = D('Weixin/User');
        $count = $user->getTeachNum($userid);
        $page = $this->Pages($count, 5);
        
        $list = $user->getTeachList($userid, $page->firstRow, $page->listRows);
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
    }
    
    /**
     * 个人资料
     */
    public function person()
    {
        if($_POST)
        {
            $post=I('post.');
            if(empty($post)){
                $this->error('信息更新失败!');
            }
            $result = M('User')->where(array('userid'=>$this->userid))->save($post);
            if($result!==false){
                $this->success('您的资料更新成功!');
            }else{
                $this->error('您的资料更新失败');
            }
        }
        $userid = $this->isLogin();
        $userInfo = M('User')->where(array('userid' => $userid))->find();
        $province = M('Province')->field('province_id,province_name')->select();
        $this->assign('province', $province);
        if(!empty($userInfo['ucity']) && !empty($userInfo['uprovince']))
        {
            $ucity = M('City')->where(array('province_id' => $userInfo['uprovince']))->select();
            $this->assign('ucity', $ucity);
        }
        if(!empty($userInfo['ucity']) && !empty($userInfo['uarea'])){
            $uarea=M('Area')->where(array('city_id'=>$userInfo['ucity']))->select();
            $this->assign('uarea', $uarea);
        }
        $this->assign('info', $userInfo);
        $this->display();
    }
    
    //获取市
    public function getcity(){
        $pid=I('get.pid');
        $citylist=M('City')->where(array('province_id'=>$pid))->select();
        foreach($citylist as $k=>$v){
            $citylist[$k]['id']=$v['city_id'];
            $citylist[$k]['name']=$v['city_name'];
        }
        echo json_encode($citylist);
    }
    
    //获取地区
    public function getarea(){
        $pid=I('get.pid');
        $arealist=M('Area')->where(array('city_id'=>$pid))->select();
        foreach($arealist as $k=>$v){
            $arealist[$k]['id']=$v['area_id'];
            $arealist[$k]['name']=$v['area_name'];
        }
        echo json_encode($arealist);
    }
    
    /**
     * 消息列表
     */
    public function sysList()
    {
        $userid = $this->isLogin();
        $count = $this->get_msg_num();
        $this->assign('count', $count);
        $this->display();
    }
    
    /**
     * 点赞收藏
     */
    public function digfav()
    {
        $userid = $this->isLogin();
        $dig = M('Dig');
    	$fav = M('UserFavorite');
    	$ypage = I('get.page');
    	if(empty($ypage))
    	{
    		$ypage = 1;
    	}
    	//$count = $this->get_digfav_num();
    	
    	$set_read = $this->set_read_status('digfav');
    //	$count = $all_count['digfav'];
    	$dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.type=1 and A.is_del=0", array($this->userid))->count();
    	$fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.is_del=0", array($this->userid))->count();
    	$count = $dig_count + $fav_count;
    	$page = $this->Pages($count, 10);
    	
    	$dig_field = array('A.id', 'A.userid' => 'touser', 'A.digtype', 'A.create_time', 'B.workid', 'B.title', 'B.type', 'B.image', 'B.userid', 'B.copyid');
    	$dig_info = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->field($dig_field)->where("B.userid=%d and A.status=1 and A.type=1 and A.is_del=0", array($this->userid))->select();
    	$dig_info = $this->set_arr($dig_info, "dig");
    	
    	$fav_field = array('A.id', 'A.userid' => 'touser', 'A.create_time', 'B.workid', 'B.title', 'B.type', 'B.image', 'B.userid', 'B.copyid');
    	$fav_info = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->field($fav_field)->where("B.userid=%d and A.status=1 and A.is_del=0", array($this->userid))->select();
    	$fav_info = $this->set_arr($fav_info, "fav");
    	
    	$yarr = array();
    	if($dig_info)
    	{
    		$yarr = array_merge_recursive($dig_info);
    	}
    	if($fav_info)
    	{
    		if($yarr)
    		{
    			$yarr = array_merge_recursive($yarr, $fav_info);
    		}
    		else 
    		{
    			$yarr = array_merge_recursive($fav_info);
    		}
    	}
    	
    	usort($yarr, function($a, $b) {
    		$al = $a['create_time'];
    		$bl = $b['create_time'];
    		if ($al == $bl)
    			return 0;
    		return ($al > $bl) ? -1 : 1;
    	});
    	
    	$list = array();
    	$start = ($ypage-1)*$page->listRows;
    	for($i = $start; $i < ($start + $page->listRows); $i++)
    	{
    		if(!empty($yarr[$i]))
    		{
    			$list[] = $yarr[$i];
    		}
    	}
    	
    	foreach($list as $k => $v)
    	{
    		$user = M('User')->where(array("userid" => $v['touser']))->find();
    		$list[$k]['nickname'] = $user['nickname'];
    		$list[$k]['openuid'] = $user['openuid'];
    		$list[$k]['uavatar'] = $user['uavatar'];
    		$list[$k]['name'] = getMsgType($v['type']);
    		$list[$k]['title'] = getMsgTitle($v['type'], $v['workid']);
    		$list[$k]['create_time'] = format_time($v['create_time'], $v['create_time']);
    		if($v['type'] == 1)
    		{
    		    $list[$k]['url'] = U('Work/detail').'?workid='.$v['workid'];
    		}
    	}
    	if($_GET['code'] == 'getPage')
    	{
    	    if(count($list) > 0)
    	    {
    	        $this->success($list);
    	    }
    	    $this->error('fail');
    	}
    	$this->assign("list", $list);
    	$this->display();
    }
    
    public function set_arr($arr, $type)
    {
        if(empty($arr))
        {
            return array();
        }
        else
        {
            foreach($arr as $k => $v)
            {
                $arr[$k]['type_name'] = $type;
            }
        }
        return $arr;
    }
    
    public function fans()
    {
        $userid = $this->isLogin();
        $model = M('UserFans');
        $set_read = $this->set_read_status('fans');
        $count = M('UserFans')->where("is_del=0 and userid=%d and status=1", array($this->userid))->count();
         
        $page = $this->Pages($count, 10);
        $field = array('id', 'myid', 'create_time', 'userid');
        $list = $model->field($field)->where("is_del=0 and userid=%d and status=1", array($this->userid))->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $user = M('User')->where(array("userid" => $v['myid']))->find();
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['openuid'] = $user['openuid'];
                $list[$k]['uavatar'] = $user['uavatar'];
                $list[$k]['isFans'] = M('UserFans')->where(array('myid' => $v['userid'], 'userid' => $v['myid'], 'status' => true))->count();
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 作品审核
     * @return number
     */
    public function pro()
    {
        $userid = $this->isLogin();
        $ypage = I('get.page');
        if(empty($ypage))
        {
            $ypage = 1;
        }
        $suipai = M('Suipai');
        $works = M('Works');
        //     	$suipai_count = $suipai->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
        //     	$works_count = $works->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
        //     	$count = $suipai_count + $works_count;
        $set_read = $this->set_read_status('pro');
         
        $suipai_count = M('Suipai')->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->count();
        $works_count = M('Works')->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->count();
        $count = $suipai_count + $works_count;
         
        $page = $this->Pages($count, 10);
         
        $suipai_info = $suipai->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->order('create_time desc')->select();
        $suipai_info = $this->set_arr($suipai_info, "suipai");
        $works_info = $works->where("status!=0 and is_del=0 and userid=%d", array($this->userid))->order('create_time desc')->select();
        $works_info = $this->set_arr($works_info, "works");
        //print_r($works_info);
         
        $yarr = array();
        if($suipai)
        {
            $yarr = array_merge_recursive($suipai_info);
        }
        if($works_info)
        {
            if($yarr)
            {
                $yarr = array_merge_recursive($yarr, $works_info);
            }
            else
            {
                $yarr = array_merge_recursive($works_info);
            }
        }
         
        usort($yarr, function($a, $b) {
            $al = $a['create_time'];
            $bl = $b['create_time'];
            if ($al == $bl)
                return 0;
            return ($al > $bl) ? -1 : 1;
        });
             
        $list = array();
        $start = ($ypage-1)*$page->listRows;
        for($i = $start; $i < ($start + $page->listRows); $i++)
        {
            if(!empty($yarr[$i]))
            {
                $list[] = $yarr[$i];
            }
        }
             
        foreach($list as $k => $v)
        {
            if($v['type_name'] == 'suipai')
            {
                $list[$k]['type'] = 4;
                $list[$k]['title'] = getMsgTitle(4, $v['id']);
                $list[$k]['url'] = '/weixin/suipai/detail?id='.$v['id'];
            }
            else
            {
                $list[$k]['type'] = 1;
                $list[$k]['title'] = getMsgTitle(1, $v['workid']);
                $list[$k]['url'] = '/weixin/work/detail?workid='.$v['id'];
            }
            if(empty($v['modify_time']))
            {
                $list[$k]['modify_time'] = $v['create_time'];
            }
            $list[$k]['modify_time'] = format_time($list[$k]['modify_time'], 'Y-m-d H:i');
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 参考作品
     */
    public function copypro()
    {
        $userid = $this->isLogin();
        $works = M('Works');
         
        $set_read = $this->set_read_status('copypro');
         
        $where = "A.is_delto=0 and B.userid=".$this->userid;
        $count = $works->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->count();
         
        $page = $this->Pages($count, 10);
         
        $list = $works->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->field("A.workid as copywork, A.userid as copyuser, A.image as copyimg, A.create_time, B.workid, B.title")->order('create_time DESC')->limit($page->firstRow . ',' . $page->listRows)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $user = M('User')->field("nickname, openuid, uavatar")->where(array('userid' => $v['copyuser']))->find();
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['openuid'] = $user['openuid'];
                $list[$k]['uavatar'] = $user['uavatar'];
                $list[$k]['title'] = getMsgTitle(1, $v['workid']);
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d H:i');
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    public function message()
    {
        $userid = $this->isLogin();
        $model=M('UserMessage');
        $list1 = array();
        $list2 = array();
        $list3 = array();
        $list4 = array();
        $count1 = $model->where("is_del=0 and touserid=".$this->userid." and type in(1, 4, 7)")->count();
        $field1 = array('infoid','content','create_time','status','id','ifread','type','userid','touserid');
        $list1 = $model->field($field1)->where("is_del=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->select();
         
        $count2 = $model->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.is_del=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $field2 = array('A.infoid','A.content','A.create_time','A.status','A.id','A.ifread','A.type','A.userid','A.touserid');
        $list2 = $model->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->field($field2)->where("A.is_del=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->select();
         
        $count3 = $model->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.is_del=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $field3 = array('D.infoid','D.content','D.create_time','D.status','D.id','D.ifread','D.type','D.userid','D.touserid');
        $list3 = $model->alias('D')->join(C('DB_PREFIX').'suipai B on D.infoid=B.id', 'LEFT')->field($field3)->where("D.is_del=0 and D.type=4 and (D.touserid is NULL OR D.touserid<>".$this->userid.") and B.userid=".$this->userid)->select();
         
        $count4 = $model->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.is_del=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $field4 = array('D.infoid','D.content','D.create_time','D.status','D.id','D.ifread','D.type','D.userid','D.touserid');
        $list4 = $model->alias('D')->join(C('DB_PREFIX').'teachlist B on D.infoid=B.teachid', 'LEFT')->field($field4)->where("D.is_del=0 and D.type=7 and (D.touserid is NULL OR D.touserid<>".$this->userid.") and B.userid=".$this->userid)->select();
        
        $ypage = empty($_GET['page']) ? 1 : intval($_GET['page']);
        $set_read = $this->set_read_status('message');
        //	$count = $all_count['message'];
        $count = $count1 + $count2 + $count3 + $count4;
        $page = $this->Pages($count, 10);
        $arr = array();
        if($list1)
        {
            $arr = array_merge_recursive($list1);
        }
        if($list2)
        {
            if($arr)
            {
                $arr = array_merge_recursive($arr, $list2);
            }
            else
            {
                $arr = array_merge_recursive($list2);
            }
        }
        if($list3)
        {
            if($arr)
            {
                $arr = array_merge_recursive($arr, $list3);
            }
            else
            {
                $arr = array_merge_recursive($list3);
            }
        }
        if($list4)
        {
            if($arr)
            {
                $arr = array_merge_recursive($arr, $list4);
            }
            else
            {
                $arr = array_merge_recursive($list4);
            }
        }
         
        //	$arr = array_merge_recursive($list1, $list2, $list3);
        usort($arr, function($a, $b) {
            $al = $a['id'];
            $bl = $b['id'];
            if ($al == $bl)
                return 0;
            return ($al > $bl) ? -1 : 1;
        });
             
        $list = array();
        if($arr)
        {
            $start = ($ypage-1)*$page->listRows;
            for($i = $start; $i < ($start + $page->listRows); $i++)
            {
                if(!empty($arr[$i]))
                {
                    $list[] = $arr[$i];
                }
            }
             
            foreach($list as $k=>$v){
                if($v['type'] == 1)
                {   
                    $list[$k]['msg'] = "在你的烘焙作品";
                    if(!empty($v['touserid']))
                    {
                        $list[$k]['msg'] = "回复了你在烘焙作品";
                    }
                }
                if($v['type'] == 4)
                {
                    $list[$k]['msg'] = "在你的随拍作品";
                    if(!empty($v['touserid']))
                    {
                        $list[$k]['msg'] = "回复了你在随拍作品";
                    }
                }
                if($v['type'] == 7)
                {
                    $list[$k]['msg'] = "在你的话题文章";
                    if(!empty($v['touserid']))
                    {
                        $list[$k]['msg'] = "回复你再话题文章";
                    }
                }
                $list[$k]['content'] = hy_substr($v['content'], 25, true);
                if($v['userid'] == 0)
                {
                    $user['nickname'] = "烘焙圈";
                }
                else
                {
                    $user = M('User')->where(array('userid' => $v['userid']))->field("nickname, uavatar, openuid")->find();
                }
                $list[$k]['user'] = $user;
                $list[$k]['title'] = getMsgTitle($v['type'], $v['infoid']);
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d H:i');
                
                $parent_id = M("UserMessage")->where(array('id' => $v['id']))->getField('parent_id');
                $yf_id = $v['id'];
                if($parent_id != 0)
                {
                    $yf_id = $parent_id;
                }
                $info = M("UserMessage")->where(array('infoid' => $v['infoid'], 'parent_id' => 0, 'type' => $v['type']))->order("create_time desc")->field("id")->select();
                $ids = array_map('array_shift', $info);
                $count = array_keys($ids, $yf_id, true);
                $page = ceil(($count[0] + 1) / C('YF_PAGE'));
                $list[$k]['url'] = '/weixin/index/msgList?page='.$page.'&type='.$v['type'].'&msgid='.$v['id'].'&id='.$v['infoid'].'#msg_'.$v['id'];
            }
        }
        
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 积分
     */
    public function score()
    {
        $userid = $this->isLogin();
        $score = M('UserDynamic');
         
        $set_read = $this->set_read_status('score');
         
        $count = M('UserDynamic')->where("status=1 and is_del=0 and userid=%d", array($this->userid))->count();
         
        $page = $this->Pages($count, 10);
         
        $list = $score->where("status=1 and is_del=0 and userid=%d", array($this->userid))->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                if($v['action'] == 'workadd' || $v['action'] == 'worksindex')
                {
                    $list[$k]['type'] = 1;
                    $list[$k]['title'] = getMsgTitle(1, $v['infoid']);
                    $list[$k]['copy_type'] = M('Works')->where(array('workid' => $v['infoid']))->getField("type");
                }
                if($v['action'] == 'spadd')
                {
                    $list[$k]['type'] = 4;
                    $list[$k]['title'] = getMsgTitle(4, $v['infoid']);
                }
                if($v['action'] == 'gift')
                {
                    $list[$k]['image'] = M('Gifts')->where(array('id' => $v['infoid']))->getField("image");
                }
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d H:i');
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 试用申请
     */
    public function listtry()
    {
        $userid = $this->isLogin();
        $try = M('TryApply');
         
        $set_read = $this->set_read_status('listtry');
         
        $count = M('TryApply')->where('status <> 0 and userid='.$this->userid." and is_del=0")->count();
         
        $page = $this->Pages($count, 10);
        $list = $try->alias("A")->join(C('DB_PREFIX')."try_items B ON A.tryid=B.tryid", "LEFT")->field('A.id, A.tryid, A.userid, A.status, B.title, A.create_time, B.image')->where('A.status <> 0 and A.userid='.$this->userid." and A.is_del=0")->order('A.create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
         
        if($list)
        {
            foreach($list as $k => $v)
            {
                $user = M('User')->where(array('userid' => $this->userid))->field('nickname, openuid, uavatar')->find();
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['openuid'] = $user['openuid'];
                $list[$k]['uavatar'] = $user['uavatar'];
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d H:i');
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 官方通知
     */
    public function sysmsg()
    {
        $userid = $this->isLogin();
        $sys = M('Sysmsg');
         
        $ids = $sys->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
        if($ids)
        {
            $arr = array();
            foreach($ids as $k => $v)
            {
                $temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('is_del');
                if(!isset($temp_type))
                {
                    $info['sysid'] = $v['id'];
                    $info['userid'] = $this->userid;
                    $info['ifread'] = 0;
                    M('SysmsgLog')->data($info)->add();
                    $arr[] = $v;
                }
                if($temp_type == 0)
                {
                    $arr[] = $v;
                }
            }
        }
         
        $ypage = I('get.page');
        $ypage = empty($ypage) ? 1 : $ypage;
        $set_read = $this->set_read_status('sysmsg');
        $count = count($arr);
        $page = $this->Pages($count, 10);
        $list = array();
        $start = ($ypage-1)*$page->listRows;
        for($i = $start; $i < ($start + $page->listRows); $i++)
        {
            if(!empty($arr[$i]))
            {
                $arr[$i]['logid'] = M('SysmsgLog')->where('sysid='.$arr[$i]['id']." and userid=".$this->userid)->getField("id");
                $arr[$i]['create_time'] = format_time($arr[$i]['create_time'], 'Y-m-d H:i');
                $list[] = $arr[$i];
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 我写的邮件
     */
    public function sendmsg()
    {
        $userid = $this->isLogin();
        $sysmsg = M('Sysmsg');
        // $this->userid = 819;
        $where = "status=1 and sendtype=2 and userid=".$this->userid." and ifread=0";

        $all_count = $this->get_msg_num();
        $count = $all_count['sendmsg'];
        $page = $this->Pages($count, 6);
         
        $list = $sysmsg->where($where)->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $user = M('User')->where(array('userid' => $v['userid']))->find();
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['openuid'] = $user['openuid'];
                $list[$k]['uavatar'] = $user['uavatar'];
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d H:i');
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
    /**
     * 发送站内信
     */
    public function sendmail()
    {
        $userid = $this->isLogin();
        if($_POST)
        {
            $post=I('post.');
            if(empty($post['title'])){
                $this->error('请填写站内信主题');
            }
            if(empty($post['content'])){
                $this->error('请填写站内信内容');
            }
            $post['userid']=$this->userid;
            $post['type']=0; //1表示系统消息,2表示会员消息
            $post['sendtype']=2;// 1表示收到,2表示发送
            $post['ifread']=0;//yf 0929
            $post['status']=true;
            $post['create_time']=time();
            $result=M('Sysmsg')->add($post);
            if($result){
                $this->success('成功发布站内信', U('User/sendmsg'));
            }else {
                $this->error('站内信发布失败');
            }
        }
        $this->display();
    }
    
    /**
     * 获取信息数量
     * @return multitype:number NULL
     */
    public function get_msg_num()
    {
        $arr = array();
         
        $message1 = M('UserMessage')->where("ifread=0 and touserid=".$this->userid." and type in(1, 4, 7)")->count();
        $message2 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.ifread=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $message3 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.ifread=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $message4 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.ifread=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->count();
        $arr['message'] = $message1 + $message2 + $message3 + $message4;
         
        $arr['digfav'] = $this->get_digfav_num();
         
        $arr['fans'] = M('UserFans')->where("ifread=0 and userid=%d and status=1", array($this->userid))->count();
         
        $suipai_count = M('Suipai')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
        $works_count = M('Works')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->count();
        $arr['pro'] = $suipai_count + $works_count;
         
        $where = "A.ifreadto=0 and B.userid=".$this->userid;
        $arr['copypro'] = M('Works')->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->count();
         
        $arr['score'] = M('UserDynamic')->where("status=1 and ifread=0 and userid=%d", array($this->userid))->count();
         
        $arr['listtry'] = M('TryApply')->where('status <> 0 and userid='.$this->userid." and ifread=0")->count();
         
        $yarr = array();
        $ids = M('Sysmsg')->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
        if($ids)
        {
            foreach($ids as $k => $v)
            {
                $temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('ifread');
                if(!isset($temp_type))
                {
                    $info['sysid'] = $v['id'];
                    $info['userid'] = $this->userid;
                    $info['ifread'] = 0;
                    $info['is_del'] = 0;
                    M('SysmsgLog')->data($info)->add();
                    $yarr[] = $v;
                }
                if($temp_type == 0)
                {
                    $yarr[] = $v;
                }
            }
        }
        $arr['sysmsg'] = count($yarr);
         
        $where2 = "status=1 and sendtype=2 and userid=".$this->userid." and ifread=0";
        $arr['sendmsg'] = M('Sysmsg')->where($where2)->count();
         
        return $arr;
    }
    
    public function set_read_status($type)
    {
        if($type == 'message')
        {
            $message1 = M('UserMessage')->where("ifread=0 and (touserid=".$this->userid." or (type=2 and infoid=".$this->userid."))")->field('id')->select();
            $message2 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'works B on A.infoid=B.workid', 'LEFT')->where("A.ifread=0 and A.type=1 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->field('A.id')->select();
            $message3 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'suipai B on A.infoid=B.id', 'LEFT')->where("A.ifread=0 and A.type=4 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->field('A.id')->select();
            $message4 = M('UserMessage')->alias('A')->join(C('DB_PREFIX').'teachlist B on A.infoid=B.teachid', 'LEFT')->where("A.ifread=0 and A.type=7 and (A.touserid is NULL OR A.touserid<>".$this->userid.") and B.userid=".$this->userid)->field('A.id')->select();
            //	print_r($message1);echo "<br>";print_r($message2);echo "<br>";print_r($message3);echo "<br>";
            $arr = array();
            if(!empty($message1))
            {
                $arr = array_merge_recursive($message1);
            }
            if(!empty($message2))
            {
                if(!empty($arr))
                {
                    $arr = array_merge_recursive($arr, $message2);
                }
                else
                {
                    $arr = array_merge_recursive($message2);
                }
            }
            if(!empty($message3))
            {
                if(!empty($arr))
                {
                    $arr = array_merge_recursive($arr, $message3);
                }
                else
                {
                    $arr = array_merge_recursive($message3);
                }
            }
            if(!empty($message4))
            {
                if(!empty($arr))
                {
                    $arr = array_merge_recursive($arr, $message4);
                }
                else
                {
                    $arr = array_merge_recursive($message4);
                }
            }
            if(!empty($arr))
            {
                foreach($arr as $k => $v)
                {
                    M('UserMessage')->where(array('id' => $v['id']))->save(array('ifread' => 1));
                }
            }
        }
        if($type == 'digfav')
        {
            $dig = M('Dig');
            $fav = M('UserFavorite');
            $dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.type=1 and A.ifread=0", array($this->userid))->field('id')->select();
            $fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->field('id')->select();
            if(!empty($dig_count))
            {
                foreach($dig_count as $dk => $dv)
                {
                    $dig->where(array('id' => $dv['id']))->save(array('ifread' => 1));
                }
            }
            if(!empty($fav_count))
            {
                foreach($fav_count as $fk => $fv)
                {
                    $fav->where(array('id' => $fv['id']))->save(array('ifread' => 1));
                }
            }
        }
        if($type == 'fans')
        {
            $fans = M('UserFans')->where("ifread=0 and userid=%d and status=1", array($this->userid))->field('id')->select();
            if(!empty($fans))
            {
                foreach($fans as $k => $v)
                {
                    M('UserFans')->where(array('id' => $v['id']))->save(array('ifread' => 1));
                }
            }
        }
        if($type == 'pro')
        {
            $suipai_count = M('Suipai')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->field('id')->select();
            $works_count = M('Works')->where("status!=0 and ifread=0 and userid=%d", array($this->userid))->field('workid')->select();
            if(!empty($suipai_count))
            {
                foreach($suipai_count as $sk => $sv)
                {
                    M('Suipai')->where(array('id' => $sv['id']))->save(array('ifread' => 1));
                }
            }
            if(!empty($works_count))
            {
                foreach($works_count as $wk => $wv)
                {
                    M('Works')->where(array('workid' => $wv['workid']))->save(array('ifread' => 1));
                }
            }
        }
        if($type == 'copypro')
        {
            $where = "A.ifreadto=0 and B.userid=".$this->userid;
            $copypro = M('Works')->alias("A")->join(C('DB_PREFIX')."works B ON A.copyid=B.workid", "LEFT")->where($where)->field('A.workid')->select();
            if(!empty($copypro))
            {
                foreach($copypro as $k => $v)
                {
                    M('Works')->where(array('workid' => $v['workid']))->save(array('ifreadto' => 1));
                }
            }
        }
        if($type == 'score')
        {
            $score = M('UserDynamic')->where("status=1 and ifread=0 and userid=%d", array($this->userid))->field('id')->select();
            if(!empty($score))
            {
                foreach($score as $k => $v)
                {
                    M('UserDynamic')->where(array('id' => $v['id']))->save(array('ifread' => 1));
                }
            }
        }
        if($type == 'listtry')
        {
            $try = M('TryApply')->where('status <> 0 and userid='.$this->userid." and ifread=0")->field('id')->select();
            if(!empty($try))
            {
                foreach($try as $k => $v)
                {
                    M('TryApply')->where(array('id' => $v['id']))->save(array('ifread' => 1));
                }
            }
        }
        if($type == 'sysmsg')
        {
            $ids = M('Sysmsg')->where('status=1 and sendtype=1 and (userid='.$this->userid." or userid is null) and create_time > '1438358400'")->order('create_time desc')->select();
            if($ids)
            {
                $arr = array();
                foreach($ids as $k => $v)
                {
                    $temp_type = M('SysmsgLog')->where("sysid=".$v['id']." and userid=".$this->userid)->getField('ifread');
                    if(!isset($temp_type))
                    {
                        $info['sysid'] = $v['id'];
                        $info['userid'] = $this->userid;
                        $info['ifread'] = 0;
                        M('SysmsgLog')->data($info)->add();
                        $arr[] = $v;
                    }
                    if($temp_type == 0)
                    {
                        $arr[] = $v;
                    }
                }
            }
            if(!empty($arr))
            {
                foreach($arr as $k => $v)
                {
                    M('SysmsgLog')->where(array('userid' => $this->userid, 'sysid' => $v['id']))->save(array('ifread' => 1));
                }
            }
        }
    }
    
    /**
     * 合并收藏点赞信息
     * @return number
     */
    public function get_digfav_num()
    {
        $dig = M('Dig');
        $fav = M('UserFavorite');
        $dig_count = $dig->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->count();
        $fav_count = $fav->alias("A")->join(C('DB_PREFIX').'works B ON A.infoid=B.workid', 'LEFT')->where("B.userid=%d and A.status=1 and A.ifread=0", array($this->userid))->count();
        $count = $dig_count + $fav_count;
        return $count;
    }
    
    /**
     * 试用报告
     */
    public function report()
    {
        $userid = $this->isLogin();
        $count = M('TryReport')->where(array('userid' => $userid))->count();
        $page = $this->Pages($count, 5);
        
        $list = M('TryReport')->where(array('userid' => $userid))
        ->field('*')
        ->order('create_time DESC')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['create_time'] = format_time($v['create_time'], "Y-m-d");
                $list[$k]['content'] = hy_substr($v['content'], 30);
                $list[$k]['url'] = U('Try/report?id='.$v['id']);
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    /**
     * 我的收藏
     */
    public function coll()
    {
        $userid = $this->isLogin();
        $count = M('UserFavorite')->where(array('userid' => $userid, 'status' => 1, 'type' => 1))->count();
        $page = $this->Pages($count, 6);
        
        $list = M('UserFavorite')
        ->where(array('userid' => $userid, 'status' => 1, 'type' => 1))
        ->order('create_time DESC')
        ->field('infoid')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $info = M()
                ->table(array(C('DB_PREFIX').'works'=>'W', C('DB_PREFIX').'user'=>'U'))
                ->where('W.userid=U.userid AND W.workid='.$v['infoid'])
                ->field('W.workid, W.title, W.content, W.image, W.goodnum, W.msgnum, U.nickname, U.uavatar')
                ->find();
                $info['content'] = hy_substr($info['content'], 40);
                $list[$k] = $info;
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    public function trylist()
    {
        $userid = $this->isLogin();
        
        $count = M('TryApply')->where(array('userid' => $userid))->count();
        $page = $this->Pages($count, 5);
        
        $list = M('TryApply')->where(array('userid' => $userid))
        ->field('*')
        ->order('create_time DESC')
        ->limit($page->firstRow . ',' . $page->listRows)
        ->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $list[$k]['create_time'] = format_time($v['create_time'], 'Y-m-d H:i');
                switch($v['status'])
                {
                    case 1:
                        $list[$k]['statusType'] = '已审核';
                        break;
                    case 2:
                        $list[$k]['statusType'] = '不通过';
                        break;
                    default :
                        $list[$k]['statusType'] = '待审核';
                }
                $list[$k]['url'] = WEB_URL.U('try/detail?tryid='.$v['tryid']);
                $tryInfo = M('TryItems')->where(array('tryid' => $v['tryid']))->field('title, image')->find();
                $list[$k]['title'] = $tryInfo['title'];
                $list[$k]['image'] = $tryInfo['image'];
                $list[$k]['isReport'] = M('TryReport')->where(array('tryid' => $v['tryid'], 'userid' => $v['userid']))->count();
                $list[$k]['reportid'] = M('TryReport')->where(array('tryid' => $v['tryid'], 'userid' => $v['userid']))->getField('id');
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign('list', $list);
        $this->display();
    }
    
    /**
     * 我的关注
     */
    public function attend()
    {
        $userid = $this->isLogin();
        $model = M('UserFans');
        $count = M('UserFans')->where("is_del=0 and myid=%d and status=1", array($this->userid))->count();
         
        $page = $this->Pages($count, 10);
        $field = array('id', 'myid', 'create_time', 'userid');
        $list = $model->field($field)->where("is_del=0 and myid=%d and status=1", array($this->userid))->order('create_time desc')->limit($page->firstRow . ',' . $page->listRows)->select();
        if($list)
        {
            foreach($list as $k => $v)
            {
                $user = M('User')->where(array("userid" => $v['userid']))->find();
                $list[$k]['nickname'] = $user['nickname'];
                $list[$k]['openuid'] = $user['openuid'];
                $list[$k]['uavatar'] = $user['uavatar'];
            }
        }
        if($_GET['code'] == 'getPage')
        {
            if(count($list) > 0)
            {
                $this->success($list);
            }
            $this->error('fail');
        }
        $this->assign("list", $list);
        $this->display();
    }
    
}